import { getBaseUrl } from '@/services/urlconst';
import { getTenantID, requestFunComponFiex, commonManageSearchParams, getLoadMapList } from '@/utils';
import { useRequest } from 'umi';
import { contractCountSwitch, getOppositeQueryInfo, getManageTabSwitch, getSearchList } from '../mconfig';
import { ILoadMapTypeAll } from '@/common';
import { ManageCommonAPI } from '@/pages/type';
import { useMemo, useState } from 'react';

const baseUrl = getBaseUrl();

/** 获取汇总合同统计 */
const reportAllByStepService = (curRes: Record<string, any>, callback: (res: any) => void) => {
  /** 获取权限信息 */
  const queryTypeObj: Record<string, any> = contractCountSwitch(curRes);

  /** 获取统计数据  */
  const { data, loading, run } = useRequest(
    (payload: Record<string, any>) => {
      const requestURL = `${baseUrl}/contractReportController/reportAllByStep/${payload?.params}`;
      return requestFunComponFiex('POST', requestURL, payload);
    },
    {
      manual: true, //页面初始请求为 true
      onSuccess: callback,
    },
  );

  const reportAllByStepRun = (payload: Record<string, any>) => {
    let searchParams: Record<string, any> = { ...payload };

    if (searchParams?.timeRanges) {
      const [createTimeStart, createTimeEnd] = searchParams.timeRanges;
      searchParams['startTime'] = createTimeStart.format('YYYY-MM-DD 00:00:00');
      searchParams['endTime'] = createTimeEnd.format('YYYY-MM-DD 23:59:59');
      delete searchParams['timeRanges'];
    }

    searchParams['companyID'] = payload?.companyID || queryTypeObj?.companyID;
    searchParams['departmentID'] = payload?.departmentID || queryTypeObj?.departmentID;
    // searchParams["departmentID"] = "1000000000000000"
    searchParams['positionID'] = payload?.positionID || queryTypeObj?.positionID;
    searchParams['userID'] = payload?.userID || queryTypeObj?.userID;
    searchParams['params'] = queryTypeObj?.params;

    if (searchParams?.CompanDeptPos) {
      delete searchParams['CompanDeptPos'];
    }

    run(searchParams);
  };

  return {
    reportAllByStepRun: reportAllByStepRun,
    reportAllByStepLoading: loading,
    reportAllByStepInfo: data?.obj,
  };
};

/** 获取合同状态汇总统计 */
const reportStateByStepService = (curRes: Record<string, any>, callback: (res: any) => void) => {
  /** 获取权限信息 */
  const queryTypeObj: Record<string, any> = contractCountSwitch(curRes);

  /** 需要翻译的数据字典 */
  const loadMapStr: string[] = [`${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}`];

  /** 获取统计数据  */
  const { data, loading, run } = useRequest(
    (payload: Record<string, any>) => {
      const bodyParams: Record<string, any> = {
        ...payload,
        sort: 'state',
        dicTypeIds: loadMapStr?.toString(),
      };

      const requestURL = `${baseUrl}/contractReportController/reportStateByStep/${bodyParams?.params}`;
      return requestFunComponFiex('POST', requestURL, bodyParams);
    },
    {
      manual: true, //页面初始请求为 true
      onSuccess: callback,
    },
  );

  const reportStateByStepRun = (payload: Record<string, any>) => {
    let searchParams: Record<string, any> = { ...payload };

    if (searchParams?.timeRanges) {
      const [createTimeStart, createTimeEnd] = searchParams.timeRanges;
      searchParams['startTime'] = createTimeStart.format('YYYY-MM-DD HH:mm:ss');
      searchParams['endTime'] = createTimeEnd.format('YYYY-MM-DD HH:mm:ss');
      delete searchParams['timeRanges'];
    }

    searchParams['companyID'] = payload?.companyID || queryTypeObj?.companyID;
    searchParams['departmentID'] = payload?.departmentID || queryTypeObj?.departmentID;
    searchParams['positionID'] = payload?.positionID || queryTypeObj?.positionID;
    searchParams['userID'] = payload?.userID || queryTypeObj?.userID;
    searchParams['params'] = queryTypeObj?.params;

    if (searchParams?.CompanDeptPos) {
      delete searchParams['CompanDeptPos'];
    }

    run(searchParams);
  };

  return {
    reportStateByStepRun: reportStateByStepRun,
    reportStateByStepLoading: loading,
    reportStateByStepInfo: data?.obj,
  };
};

/** 获取合同相对方汇总统计 */
const reportOppositeByStepService = (curRes: Record<string, any>, callback: (res: any) => void) => {
  /** 获取权限信息 */
  const queryTypeObj: Record<string, any> = contractCountSwitch(curRes);

  /** 需要翻译的数据字典 */
  const loadMapStr: string[] = [`${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}`];

  /** 获取统计数据  */
  const { data, loading, run } = useRequest(
    (payload: Record<string, any>) => {
      const bodyParams: Record<string, any> = {
        ...payload,
        sort: 'state',
        dicTypeIds: loadMapStr?.toString(),
        capitalDir: '0',
        state: `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1004,${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1005`,
      };

      const requestURL = `${baseUrl}/contractReportController/reportOppositeByStep/${bodyParams?.params}`;
      return requestFunComponFiex('POST', requestURL, bodyParams);
    },
    {
      manual: true, //页面初始请求为 true
      onSuccess: callback,
    },
  );

  const reportOppositeByStepRun = (payload: Record<string, any>) => {
    let searchParams: Record<string, any> = { ...payload };
    if (searchParams?.timeRanges) {
      const [createTimeStart, createTimeEnd] = searchParams.timeRanges;
      searchParams['startTime'] = createTimeStart.format('YYYY-MM-DD HH:mm:ss');
      searchParams['endTime'] = createTimeEnd.format('YYYY-MM-DD HH:mm:ss');
      delete searchParams['timeRanges'];
    }

    searchParams['companyID'] = payload?.companyID || queryTypeObj?.companyID;
    searchParams['departmentID'] = payload?.departmentID || queryTypeObj?.departmentID;
    searchParams['positionID'] = payload?.positionID || queryTypeObj?.positionID;
    searchParams['userID'] = payload?.userID || queryTypeObj?.userID;
    searchParams['params'] = queryTypeObj?.params;

    if (searchParams?.supplierID?.length > 0) {
      searchParams['supplierID'] = searchParams?.supplierID?.toString();
    } else {
      delete searchParams['supplierID'];
    }

    if (searchParams?.CompanDeptPos) {
      delete searchParams['CompanDeptPos'];
    }

    run(searchParams);
  };

  return {
    reportOppositeByStepRun: reportOppositeByStepRun,
    reportOppositeByStepLoading: loading,
    reportOppositeByStepInfo: data?.obj,
  };
};

/**
 * dataGrid 合同主体
 * @param curRes 权限
 * @param supplierInfo 确认合同主体或者相对方
 * @returns
 */
const getOppositeDataGrid = (curRes: Record<string, any>, supplierInfo: Record<string, any>) => {
  /** 获取权限参数 */
  const queryObj: Record<string, any> = getOppositeQueryInfo(curRes);

  /** 获取列表数据  */
  const { loading, data, run } = useRequest(
    (opt: ManageCommonAPI.IGridRequestType) => {
      const requestBody: Record<string, any> = {
        current: 1,
        pageSize: 9999,
        sort: 'createTime',
        order: 'desc',
        ...supplierInfo,
        ...queryObj,
        ...opt,
        creditID: `12100000MB2001605R,12110000MB1N5794X2`,
        selectSign: false,
      };

      const requestURL = `${baseUrl}/contractController/oppositeDataGrid/${requestBody?.params}`;
      return requestFunComponFiex('POST', requestURL, requestBody);
    },
    {
      manual: true, //页面初始请求为 true
      paginated: true,
      defaultPageSize: 9999,
    },
  );

  /**  获取管理也数据  */
  const getManageData = (otherRequest: ManageCommonAPI.IGridRequestType | any) => {
    const request: ManageCommonAPI.IGridRequestType | any = {
      ...otherRequest,
    };

    delete request['supplierName'];

    run({ ...request });
  };

  return {
    oppositeLoading: loading,
    oppositeList: data?.rows,
    getManageData: getManageData,
  };
};

const contractManageService = (curRes: Record<string, any>, pageParams: Record<string, any> | null) => {
  /**  需要获取的数据字典 */
  const loadMdicIds: string[] = [
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_TYPE}`, //合同类型
    `${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`, //采购方式
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}`, //合同状态
    `${getTenantID()}${ILoadMapTypeAll.PAYMENT_STYLE}`, //支付方式
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_CANCELTYPE}`, //作废方式
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_CURRENCYTYPE}`, //币种
  ];

  /** 获取数据字典loadMdicMap */
  const loadMdicMapObj: Record<string, any> = getLoadMapList(loadMdicIds);

  /**获取权限参数 */
  const queryTypeObj: Record<string, any> = contractCountSwitch(curRes);
  /** 获取合同主体数据 */
  const dataList = [];

  /** 获取搜索参数 */
  const searchListParams = getSearchList(loadMdicMapObj?.loadMapInfo, queryTypeObj, dataList, pageParams);

  /** 保存全部搜索参数 */
  const [allSearchParams, setAllSearchParams] = useState<Record<string, any>>({});

  /** 获取列表数据  */
  const { tableProps, data, loading, run, refresh } = useRequest(
    (opt: ManageCommonAPI.IGridRequestType) => {
      let requestBody: Record<string, any> = {
        ...queryTypeObj,
        // current: 1,
        // pageSize: 10,
        // sort: 'changeFlag asc, createTime',
        // order: 'desc',
        dicTypeIds: loadMdicIds?.toString(),
        state: '100123081004,100123081005',
        ...opt,
      };
      delete requestBody['pageSize'];
      delete requestBody['current'];

      const searchParams: Record<string, any> = commonManageSearchParams(searchListParams, requestBody, {
        dicTransName: 'supplyKind,supplyType,procureReal,changeTypeName,state,payStyle,cancelType,checkState,procureOrg,businessType,currencyType',
        // orgTransName: `${ISearchTranslateAll.SIGN_DEPT},${ISearchTranslateAll.CREATER_DEPT},${ISearchTranslateAll.OWNER_DEPT},${ISearchTranslateAll.CANCEL_DEPT},${ISearchTranslateAll.DUTY_DEPT},${ISearchTranslateAll.HAND_DEPT}`,
        // areaTransName: `${ISearchTranslateAll.AREA_TRANS}`,
      });
      setAllSearchParams({
        ...requestBody,
      });
      // console.log('searchParams',searchParams)
      // const requestURL = `${baseUrl}/contractController/dataGrid/${requestBody?.params}`;
      let requestURL = `${baseUrl}/contractReportController/reportScopeByStep/${requestBody?.params}`;

      return requestFunComponFiex('POST', requestURL, requestBody);
    },
    {
      manual: true, //页面初始请求为 true
      paginated: true,
      // defaultPageSize: 10,
    },
  );

  /* 获取页面数据 */
  const getContractData = (otherRequest: ManageCommonAPI.IGridRequestType | any) => {
    const request: ManageCommonAPI.IGridRequestType | any = {
      ...otherRequest,
    };
    if (request?.realTime) {
      const [startTime, endTime] = request.realTime;
      request['startTime'] = startTime.format('YYYY-MM-DD 00:00:00');
      request['endTime'] = endTime.format('YYYY-MM-DD 23:59:59');
      delete request['realTime'];
    }

    // if (request?.cancelTime) {
    //   const [cancelTimeStart, cancelTimeEnd] = request.cancelTime;
    //   request['cancelTimeStart'] = cancelTimeStart.format('YYYY-MM-DD 00:00:00');
    //   request['cancelTimeEnd'] = cancelTimeEnd.format('YYYY-MM-DD 23:59:59');
    //   delete request['cancelTime'];
    // }

    // if (request?.preTime) {
    //   const [preBeginTime, preFinishTime] = request.preTime;
    //   request['preBeginTime'] = preBeginTime.format('YYYY-MM-DD 00:00:00');
    //   request['preFinishTime'] = preFinishTime.format('YYYY-MM-DD 23:59:59');
    //   delete request['preTime'];
    // }

    // if (request?.realTime) {
    //   const [realBeginTime, realFinishTime] = request.realTime;
    //   request['realBeginTime'] = realBeginTime.format('YYYY-MM-DD 00:00:00');
    //   request['realFinishTime'] = realFinishTime.format('YYYY-MM-DD 23:59:59');
    //   delete request['realTime'];
    // }

    // delete request['createFormNameDept'];
    // delete request['createFormNameUser'];
    // if (request?.createrID && request?.createrID?.length > 0) {
    //   request['createrID'] = request?.createrID?.toString();
    // } else {
    //   delete request['createrID'];
    // }

    run({
      ...request,
    });
  };

  /** 搜索列表  */
  const searchList = useMemo(() => {
    return {
      searchList: searchListParams,
    };
  }, [loadMdicMapObj?.loadMapInfo]);

  /** 页面列表 */
  const returnTableProps = useMemo(() => {
    return {
      data,
      pagination: tableProps?.pagination,
    };
  }, [data, tableProps]);

  return {
    loading,
    getContractData,
    reloadRefresh: refresh,
    allSearchParams,
    ...returnTableProps,
    ...searchList,
  };
};

export { reportAllByStepService, reportStateByStepService, reportOppositeByStepService, getOppositeDataGrid, contractManageService };
